package com.work.yshop.ui.activity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.work.yshop.R;
import com.work.yshop.model.Product;
import com.work.yshop.provider.ProductProvider;
import com.work.yshop.utils.ImageLoader;
import com.work.yshop.utils.ImageUtils;
import com.work.yshop.utils.UserSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 商品编辑页面
 */
public class ProductEditActivity extends AppCompatActivity {

    private static final String TAG = "ProductEditActivity";
    private static final int REQUEST_IMAGE_PICK = 100;
    
    private ImageView btnBack;
    private TextView tvTitle;
    private CardView cardImageUpload;
    private ImageView ivProductImage;
    private EditText etProductName;
    private Spinner spinnerCategory;
    private EditText etPrice;
    private EditText etStock;
    private EditText etDescription;
    private Button btnSubmit;
    private Button btnDelete;
    
    private String[] categories = {"水果", "蔬菜", "肉禽蛋", "水产", "干货", "粮油", "其他"};
    private String imageUrl = ""; // 存储图片路径
    private boolean isImageSelected = false;
    
    private int productId; // 要编辑的商品ID
    private Product product; // 商品对象

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_product);
        
        // 获取要编辑的商品ID
        productId = getIntent().getIntExtra("product_id", -1);
        if (productId == -1) {
            Toast.makeText(this, "商品ID无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        initViews();
        setupSpinner();
        setupListeners();
        
        // 加载商品数据
        loadProductData();
    }
    
    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        tvTitle = findViewById(R.id.tv_title);
        cardImageUpload = findViewById(R.id.card_image_upload);
        ivProductImage = findViewById(R.id.iv_product_image);
        etProductName = findViewById(R.id.et_product_name);
        spinnerCategory = findViewById(R.id.spinner_category);
        etPrice = findViewById(R.id.et_price);
        etStock = findViewById(R.id.et_stock);
        etDescription = findViewById(R.id.et_description);
        btnSubmit = findViewById(R.id.btn_submit);
        
        // 修改标题
        tvTitle.setText("编辑商品");
        
        // 修改提交按钮文本
        btnSubmit.setText("保存修改");
        
        // 添加删除按钮
        btnDelete = findViewById(R.id.btn_delete);
        if (btnDelete != null) {
            btnDelete.setVisibility(View.VISIBLE);
        }
    }
    
    private void setupSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> onBackPressed());
        
        cardImageUpload.setOnClickListener(v -> {
            // 启动图片选择
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_IMAGE_PICK);
        });
        
        btnSubmit.setOnClickListener(v -> updateProduct());
        
        // 删除按钮点击事件
        if (btnDelete != null) {
            btnDelete.setOnClickListener(v -> confirmDelete());
        }
    }
    
    /**
     * 加载商品数据
     */
    private void loadProductData() {
        ContentResolver resolver = getContentResolver();
        Uri productUri = Uri.withAppendedPath(ProductProvider.CONTENT_URI, String.valueOf(productId));
        
        try {
            Cursor cursor = resolver.query(productUri, null, null, null, null);
            
            if (cursor != null && cursor.moveToFirst()) {
                // 读取商品数据
                String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
                String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
                double price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
                int stock = cursor.getInt(cursor.getColumnIndexOrThrow("stock"));
                String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));
                String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
                
                // 创建商品对象
                product = new Product();
                product.setId(productId);
                product.setName(name);
                product.setDescription(description);
                product.setPrice(price);
                product.setStock(stock);
                product.setCategory(category);
                product.setImageUrl(imageUrl);
                
                // 填充表单
                etProductName.setText(name);
                etPrice.setText(String.valueOf(price));
                etStock.setText(String.valueOf(stock));
                etDescription.setText(description);
                
                // 设置图片
                this.imageUrl = imageUrl;
                if (!TextUtils.isEmpty(imageUrl)) {
                    isImageSelected = true;
                    ImageLoader.loadImage(this, imageUrl, ivProductImage);
                }
                
                // 设置分类
                for (int i = 0; i < categories.length; i++) {
                    if (categories[i].equals(category)) {
                        spinnerCategory.setSelection(i);
                        break;
                    }
                }
                
                cursor.close();
            } else {
                Toast.makeText(this, "未找到商品数据", Toast.LENGTH_SHORT).show();
                finish();
            }
        } catch (Exception e) {
            Log.e(TAG, "加载商品数据失败", e);
            Toast.makeText(this, "加载商品数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    
    /**
     * 更新商品数据
     */
    private void updateProduct() {
        // 验证输入
        String name = etProductName.getText().toString().trim();
        String priceStr = etPrice.getText().toString().trim();
        String stockStr = etStock.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        String category = spinnerCategory.getSelectedItem().toString();
        
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入商品名称", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(priceStr)) {
            Toast.makeText(this, "请输入商品价格", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(stockStr)) {
            Toast.makeText(this, "请输入商品库存", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!isImageSelected) {
            Toast.makeText(this, "请选择商品图片", Toast.LENGTH_SHORT).show();
            return;
        }
        
        double price;
        int stock;
        
        try {
            price = Double.parseDouble(priceStr);
            stock = Integer.parseInt(stockStr);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的价格和库存", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (price <= 0) {
            Toast.makeText(this, "价格必须大于0", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (stock <= 0) {
            Toast.makeText(this, "库存必须大于0", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建更新数据
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("price", price);
        values.put("stock", stock);
        values.put("description", description);
        values.put("category", category);
        values.put("image_url", imageUrl);
        
        // 设置原价（默认比售价高20%）
        double originalPrice = price * 1.2;
        values.put("original_price", originalPrice);
        
        // 设置更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String currentTime = sdf.format(new Date());
        values.put("update_date", currentTime);
        
        // 更新数据到ContentProvider
        ContentResolver resolver = getContentResolver();
        Uri productUri = Uri.withAppendedPath(ProductProvider.CONTENT_URI, String.valueOf(productId));
        int updatedRows = resolver.update(productUri, values, null, null);
        
        if (updatedRows > 0) {
            Toast.makeText(this, "商品更新成功", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();
        } else {
            Toast.makeText(this, "商品更新失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 确认删除商品
     */
    private void confirmDelete() {
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除商品 \"" + etProductName.getText().toString().trim() + "\" 吗？此操作不可恢复。")
                .setPositiveButton("删除", (dialog, which) -> deleteProduct())
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 删除商品
     */
    private void deleteProduct() {
        ContentResolver resolver = getContentResolver();
        Uri productUri = Uri.withAppendedPath(ProductProvider.CONTENT_URI, String.valueOf(productId));
        int deletedRows = resolver.delete(productUri, null, null);
        
        if (deletedRows > 0) {
            Toast.makeText(this, "商品已删除", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();
        } else {
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                // 显示选择的图片
                ivProductImage.setImageURI(selectedImageUri);
                
                // 获取图片路径
                imageUrl = ImageUtils.getPathFromUri(this, selectedImageUri);
                isImageSelected = true;
            }
        }
    }
} 